#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int res = INT_MIN;
    int recursion(TreeNode* root)
    {
        if (root == nullptr)
        {
            return 0;
        }
        int maxL = recursion(root->left);
        int maxR = recursion(root->right);
        int ret = max(root->val, max(root->val + maxL, root->val + maxR));
        int Max = max(ret, root->val + maxL + maxR);
        if (Max > res)
        {
            res = Max;
        }
        return ret;
    }
    int maxPathSum(TreeNode* root)
    {
        recursion(root);
        return res;
    }
};